<!-- 
 @Author: Havery 
 @Date: 2020-12-09 17:17:08   
 @function: 分类统计
 -->
<template>
  <div class="classified">
    <el-row :gutter="12">
      <el-col :span="19">
        <el-row :gutter="12">
          <el-col :span="6">
            <!-- 通过shadow属性设置卡片阴影出现的时机：always、hover或 never -->
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span class="tit">
                  <i class="iconfont iconxiaoxi1"></i>最新消息
                  <span class="unit" style="background-color: #FFB800;">周</span>
                </span>
              </div>
              <div class="optbtns">
                <el-row>未读信息:{{countData.unreadCount}}(条)</el-row>
                <el-row>信息总数:{{countData.messageSum}}(条)</el-row>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span class="tit">
                  <i class="iconfont iconcaozuorizhi"></i>操作动态
                  <span class="unit" style="background-color: #1E9FFF;">周</span>
                </span>
              </div>
              <div class="optbtns">
                <el-row>登录次数: {{countData.loginCount}}(次)</el-row>
                <el-row>操作次数: {{countData. operationCount}}(次)</el-row>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="never">
              <div slot="header" class="clearfix">
                <span class="tit">
                  <i class="iconfont iconcuowu"></i>系统错误
                  <span class="unit" style="background-color: #2F4056;">周</span>
                </span>
              </div>
              <div class="optbtns">
                <el-row>未解决错误: {{countData.unresolvedCount}}(个)</el-row>
                <el-row>错误总数: {{countData.errorCount}}(个)</el-row>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="never">
              <div slot="header" class="clearfix">
                <span class="tit">
                  <i class="iconfont iconanquan1"></i>安全信息
                  <span class="unit" style="background-color: #F69D73;">全</span>
                </span>
              </div>
              <div class="optbtns">
                <el-row>预警个数: {{countData.warningCount}}(个)</el-row>
                <el-row>黑名单个数: {{countData.blacklistCount}}(个)</el-row>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="12" style="margin-top:10px;">
          <el-col :span="10">
            <el-card shadow="always">
              <div slot="header" class="clearfix">
                <span class="tit">
                  <i class="iconfont iconjibenxinxi"></i>最新消息
                </span>
              </div>
              <div class="optbtns message" ref="messageRef">
                <el-timeline>
                  <el-timeline-item
                    v-for="(messageInfo, index) in messageInfos"
                    :key="index"
                    placement="top"
                    color="#409EFF"
                    size="normal"
                    :timestamp="messageInfo.create_date"
                  >
                    <el-card shadow="hover" style="margin-right:5px;margin-top:5px;">
                      <div slot="header">
                        <span>{{messageInfo.title}}</span>
                        <el-button
                          style="float: right"
                          type="primary"
                          @click="replayMassage(messageInfo)"
                          size="mini"
                        >回复</el-button>
                        <el-button
                          style="float: right;margin-right: 20px"
                          type="warning"
                          size="mini"
                          @click="removeMassage(messageInfo)"
                        >删除</el-button>
                      </div>
                      <div style="margin-right: 5px; word-break: break-all">{{messageInfo.content}}</div>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-card>
          </el-col>
          <el-col :span="14">
            <el-row>
              <el-card shadow="hover">
                <div slot="header" class="clearfix">
                  <span class="tit">
                    <i class="iconfont iconjiekou"></i>接口请求信息
                  </span>
                </div>
                <div class="optbtns" ref="apiRef">
                   <div id="lineChart" style="width:100%;height:100%;">柱状图统计</div>
                </div>
              </el-card>
            </el-row>
            <el-row style="margin-top:10px;">
              <el-card shadow="hover">
                <div slot="header" class="clearfix">
                  <span class="tit">
                    <i class="iconfont iconcuowu"></i>系统错误
                  </span>
                </div>
                <div class="optbtns" ref="errorRef">
                  <el-table
                    class="ptab"
                    border
                    stripe
                    style="width: 99%"
                    :data="sysErrorData"
                    :height="tableHeight"
                  >
                    <el-table-column prop="create_date" label="报错时间" width="160"></el-table-column>
                    <el-table-column prop="service_name" label="服务名称" width="160" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="exception_title" label="异常标题" :show-overflow-tooltip="true"></el-table-column>
                  </el-table>
                </div> 
              </el-card>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="5">
        <el-row>
          <el-card class="box-card weathercard">
            <div class="weatherbox">
              <img src="@/assets/images/first/bg.png" class="bgimg" alt />
              <div class="conrow1">
                <span class="user_name">{{userName}}</span>
                <span class="welcome"> 欢迎登陆本系统!</span>
                <span class="cityposition">
                  <i class="el-icon-location"></i> 成都市
                </span>
              </div>
              <div class="lasttime">所属部门：{{departmentName}}</div>
              <div class="weathertime">
                <div class="weatherinfo">
                  <div id="weather-v2-plugin-simple"></div>
                </div>
                <div class="curtime">
                  <div>{{nowWeek}}</div>
                  <div>{{nowTimes}}</div>
                </div>
              </div>
              <div>
                <!-- 里面写eleCalendar组件-->
                <ele-calendar
                  class="calendarbox"
                  :render-content="renderContent"
                  :data="datedef"
                  :prop="prop"
                ></ele-calendar>
              </div>
            </div>
          </el-card>
        </el-row>
        <el-row style="margin-top:10px;">
          <el-card shadow="never">
            <div slot="header" class="clearfix">
              <span class="tit">
                <i class="iconfont iconjibenxinxi"></i>最新动态
              </span>
            </div>
            <div class="optbtns message" ref="newsRef">
              <el-timeline>
                <el-timeline-item
                  v-for="(log, index) in logs"
                  :key="index"
                  placement="top"
                  size="normal"
                  :timestamp="log.create_date"
                >{{log.detail}}</el-timeline-item>
              </el-timeline>
            </div>
          </el-card>
        </el-row>
      </el-col>
    </el-row>

    <!-- 编辑等操作弹窗 -->
    <!-- dialog 弹窗顶部下划线 v-dialogDrag可拖拽-->
    <el-dialog
      :title="editForm.formTitle"
      :visible.sync="editForm.formVisible"
      v-if="editForm.formVisible"
      width="30%"
      v-dialogDrag
      custom-class="dialog"
      :close-on-click-modal="false"
    >
      <ReplayForm v-bind:formInfo="formInfo" @callBack="callBack"></ReplayForm>
    </el-dialog>
  </div>
</template>
<script>
import EleCalendar from "ele-calendar"; //日历
import "ele-calendar/dist/vue-calendar.css";
import Echarts from "echarts";
import FirstPageHttp from "@/api/first/index"; //http
import ReplayForm from "./components/replay"; //回复窗体

//定义变量
const {
  loadMessageCount, //获取对应时间段类，自己的总的消息，未读消息数量
  loadCurrentMessage, //获取最新未读信息
  loadApiMonitorCount, //获取接口预警和黑名单个数信息
  replayMassage, //回复消息
  readMassage, //查看信息
  removeMassage, //删除消息
  loadOperationCount, //获取对应时间段内，操作日志数量
  loadOperationList, //获取最新操作日志列表
  loadExceptionCount, //获取对应时间段内，异常信息数量
  loadExceptionList //获取最异常日志信息
} = FirstPageHttp;
//引用对象
export default {
  name: "firstPage",
  components: {
    EleCalendar,
    Echarts,
    ReplayForm
  },
  data() {
    return {
      //日历
      datedef: [],
      prop: "date", //对应日期字段名
      //统计个数信息
      countData: {
        unreadCount: 0, //未读信息总数
        messageSum: 0, //信息总数
        loginCount: 0, //登录次数
        operationCount: 0, //操作次数
        unresolvedCount: 0, //未解决错误数
        errorCount: 0, //错误数
        warningCount: 0, //预警数
        blacklistCount: 0 //黑名单个数
      },
      //消息列表
      messageInfos: [], 
      editForm: {//编辑框窗体参数
        formVisible: false, //窗体是否显示
        formTitle: "", //窗体标题
      },
      formInfo: {},
      logs: [], //日志列表
      //接口请求趋势      
      echartObj: {},
      //错误列表
      tableHeight: window.innerHeight * 0.31, //表格高度
      sysErrorData:[],
      //时间、天气、用户信息相关
      userName:"",
      departmentName:"",
      timer: null,
      nowWeek:"",
      nowTimes:"",
    };
  },
  computed: {},
  /**html加载完成之前，执行。执行顺序：父组件-子组件 */
  created() {},
  /**[页面初始化方法]html加载完成后执行。执行顺序：子组件-父组件*/
  mounted() {
    //调整高度
    this.adjustHeight();
    //获取用户信息
    this.loadUserInfo();
    //获取消息数量信息
    this.loadMessageCount();
    //获取最新未读信息
    this.loadCurrentMessage();
    //获取对应时间段内，操作日志数量
    this.loadOperationCount();
    //获取对应时间段内，异常信息数量
    this.loadExceptionCount();
    //获取接口预警和黑名单个数信息
    this.loadApiMonitorCount();
    //获取实时信息
    this.loadInterfaceRequest();
    //获取异常信息
    this.loadExceptionInfo();
    ////右侧////////////////////////////////////////////////
    //获取天气信息
    this.loadWeather();
    //获取操作日志
    this.loadOperationList();
  },
  //事件方法执行
  //监听方法 click事件等，执行drawFeatures方法
  methods: {
    //调整高度
    adjustHeight() {
      var h = document.documentElement.clientHeight || document.body.clientHeight;
      this.$refs.messageRef.style.height = h * 0.668 + "px";
      this.$refs.newsRef.style.height = h * 0.33 + "px";
      this.$refs.apiRef.style.height = h * 0.25 + "px";
      this.$refs.errorRef.style.height = h * 0.304 + "px";
    },
    //获取用户信息
    loadUserInfo(){
       let self=this;
       let unserInfo = this.$store.getters.userInfo;
       this.userName=unserInfo.realname;
       this.departmentName=unserInfo.department_names;
       this.nowWeek=this.loadNowTimes();
       this.timer = setInterval(() => {
            self.nowTimes=self.$moment(new Date()).format( "YYYY-MM-DD HH:mm:ss");
       }, 1000);
    },
    loadNowTimes () {
      let myDate = new Date()
      let wk = myDate.getDay()
      let yy = String(myDate.getFullYear())
      let mm = myDate.getMonth() + 1
      let dd = String(myDate.getDate() < 10 ? '0' + myDate.getDate() : myDate.getDate())
      let hou = String(myDate.getHours() < 10 ? '0' + myDate.getHours() : myDate.getHours())
      let min = String(myDate.getMinutes() < 10 ? '0' + myDate.getMinutes() : myDate.getMinutes())
      let sec = String(myDate.getSeconds() < 10 ? '0' + myDate.getSeconds() : myDate.getSeconds())
      let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      return weeks[wk];
    },
    //获取消息数量信息
    loadMessageCount() {
      let par = {
        beginTime: this.$moment(this.loadPastTime(7)).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        endTime: this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
      };
      loadMessageCount(par).then(response => {
        let result = response.data;
        if (result.Code === 1000) {
          this.countData.unreadCount = result.Data.unread_count;
          this.countData.messageSum = result.Data.total;
        } 
      });
    },
    //获取对应时间段内，操作日志数量
    loadOperationCount() {
      let par = {
        beginTime: this.$moment(this.loadPastTime(7)).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        endTime: this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
      };
      loadOperationCount(par).then(response => {
        let result = response.data;
        if (result.Code === 1000) {
          this.countData.loginCount = result.Data.login_times;
          this.countData.operationCount = result.Data.operation_times;
        } 
      });
    },
    //获取对应时间段内，异常信息数量
    loadExceptionCount() {
      let par = {
        beginTime: this.$moment(this.loadPastTime(7)).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        endTime: this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
      };
      loadExceptionCount(par).then(response => {
        let result = response.data;
        if (result.Code === 1000) {
          this.countData.unresolvedCount = result.Data.unresolved_count;
          this.countData.errorCount = result.Data.total;
        } 
      });
    },
    //获取接口预警和黑名单个数信息
    loadApiMonitorCount() {
      let par = {};
      loadApiMonitorCount(par).then(response => {
        let result = response.data;
        if (result.Code === 1000) {
          this.countData.warningCount = result.Data.warningCount;
          this.countData.blacklistCount = result.Data.blacklistCount;
        } 
      });
    },
    /////////////////////////////////////
    //获取最新未读信息
    loadCurrentMessage() {
      let par = {
        beginTime: this.$moment(this.loadPastTime(7)).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        endTime: this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
      };
      loadCurrentMessage(par).then(response => {
        let result = response.data;
        if (result.Code === 1000) {
          for (let index = 0; index < result.Data.length; index++) {
            result.Data[index].create_date = this.$moment(
              result.Data[index].create_date
            ).format("YYYY年MM月DD日 HH点mm分");
          }
          this.messageInfos = result.Data;
        }
      });
    },
    //获取实时信息
    loadInterfaceRequest() {
      let self = this;
      let signalRUrl = this.$store.state.config.devopsURI + "/apiMonitorLog";
      this.$signalR.startCon(signalRUrl, function(connection) {

        let beginTime = self.$moment(new Date().setSeconds(-60)).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        let endTime = self.$moment(new Date()).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        ///巡检和养护信息统计图（展示累计总的任务数量，当日巡检的任务数量、已完成数量，累计养护任务数量，当日养护任务数量，已完成数量）
        connection.on("InterfaceRequestMsg", function(result) {
           if (result.code==1000) {
              self.loadLineEchart(result);
           }
        });
        connection.invoke("InterfaceRequestInfo", beginTime, endTime).catch(function(err) {
          return console.error(err.toString());
        });
        let timer=setInterval(function() {
          if (document.getElementById("lineChart")) {
              beginTime = self.$moment(new Date().setSeconds(-60)).format("YYYY-MM-DD HH:mm:ss");
              endTime = self.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
              connection.invoke("InterfaceRequestInfo", beginTime, endTime).catch(function(err) {
                return console.error(err.toString());
              });
          }else {
            clearInterval(this.timer);     
          }
        }, 10000);
      });
    },
    //编辑界面
    replayMassage(messageInfo) {
      this.editForm.formVisible = true;
      if (messageInfo != null && messageInfo != undefined) {
        this.editForm.formTitle = "回复信息";
        //不要直接赋值，不然造成-引用类型传递
        this.formInfo ={
          id:messageInfo.id,
          receiver_id:messageInfo.sender_id
        } 
      }
    },
    //消息返回
    callBack(id){
      if(id!=null){
        let par ={ id:id};
        readMassage(par).then(response => {
          let data = response.data;
          if (data.Code === 1000) {
            this.loadCurrentMessage();
            this.loadMessageCount();
          }
        });
      }
      this.editForm.formVisible = false;
    },
    //删除消息
    removeMassage(messageInfo){
      this.$messageTip.boxWarning("确定要删除吗?")
      .then(() => {
          let par = [];
          par.push(messageInfo.id);
          removeMassage(par).then(response => {
            let data = response.data;
            if (data.Code === 1000) {
              this.$messageTip.success(data.Msg);
              this.loadCurrentMessage();
              this.loadMessageCount();
            } else {
              this.$messageTip.warning(data.Msg); 
            }
          });
        })
        .catch(() => {
           this.$messageTip.info("已取消删除！"); 
        });
    },
    ///////////////////////////////////////
    //加载折线图
    loadLineEchart(result){
        this.myChart = Echarts.init(document.getElementById("lineChart"));
        var option = {
          tooltip: {
            trigger: "axis",
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data:  result.data != null ? result.data.xAxis:[]
          },
          yAxis: {
             type: 'value'
          },
         series:[{
              type: 'line',
              label: {
                  show: true
              },
              data: result.data != null ? result.data.yAxis:[],
              lineStyle: {
                  color: {
                      type: 'linear',
                      x: 0,
                      y: 0,
                      x2: 0,
                      y2: 1,
                      colorStops: [{
                          offset: 0, color: 'red' // 0% 处的颜色
                      }, {
                          offset: 1, color: 'blue' // 100% 处的颜色
                      }],
                      global: false // 缺省为 false
                  }
              }
          }],
          grid: {
              show: false,
              x: 50,
              x2: 40,
              y: 32
          },
        };
        this.myChart.setOption(option,true);
        this.myChart.resize();
    },
    /////////////////////////////////////
    //获取异常信息
    loadExceptionInfo(){
      let par = {};
      loadExceptionList(par).then(response => {
        let result = response.data;
        if (result.Code === 1000) {
          
          for (let index = 0; index < result.Data.length; index++) {
              result.Data[index].create_date = this.$moment(result.Data[index].create_date).format("MM月DD日 HH点mm分");
          }
          this.sysErrorData=result.Data;
        } 
      });
    },
    ////右侧////////////////////////////////////////////////
    //加载天气
    loadWeather() {
      window.WIDGET = {
        CONFIG: {
          modules: "20",
          background: 5,
          tmpColor: "FFFFFF",
          tmpSize: "36",
          cityColor: "FFFFFF",
          citySize: 16,
          aqiSize: 16,
          weatherIconSize: 24,
          alertIconSize: 18,
          language: "auto",
          borderRadius: 5,
          fixed: "false",
          vertical: "middle",
          horizontal: "left",
          key: "RQYLoQAKjI"
        }
      };
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src =
        "https://apip.weatherdt.com/simple/static/js/weather-simple-common.js?v=2.0";
      document.getElementsByTagName("head")[0].appendChild(script);
    },
    //加载日历
    renderContent(h, parmas) {
      const loop = data => {
        return data.defvalue.value ? (
          <div>
            <div>{data.defvalue.text}</div>
            <span>备选项</span>
          </div>
        ) : (
          <div>{data.defvalue.text}</div>
        );
      };
      return <div class="unitdata">{loop(parmas)}</div>;
    },
    //获取操作日志
    loadOperationList() {
      let par = {};
      loadOperationList(par).then(response => {
        let result = response.data;
        if (result.Code === 1000) {
          for (let index = 0; index < result.Data.length; index++) {
            result.Data[index].create_date = this.$moment(
              result.Data[index].create_date
            ).format("YYYY年MM月DD日 HH点mm分");
            result.Data[index].detail =
              result.Data[index].user_name +
              "-" +
              this.ellipsis(result.Data[index].detail);
          }
          this.logs = result.Data;
        } else {
          this.$messageTip.warning(data.Msg); 
        }
      });
    },
    //过去时间
    loadPastTime(day) {
      var pastDay = new Date();
      pastDay.setDate(pastDay.getDate() - day);
      return pastDay;
    },
    //根据字符串的长度控制显示的字数超出显示省略号
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 20) {
        return value.slice(0, 20) + "...";
      }
      return value;
    }
  }
};
</script>
 <style lang="scss" scoped>
.tit {
  font-size: 16px;
  font-family: " Microsoft YaHei";
  color: #4c4f53;
}
.optbtns {
  font-size: 14px;
  font-family: " Microsoft YaHei";
  color: #4c4f53;
}
.message {
  overflow: auto;
}
.message::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.message::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #aba9a9;
}
.message::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #ededed;
}
.unit {
  padding: 0 6px 2px;
  color: #fff;
}
.weatherbox {
  width: 100%;
  height: 465px;
}
.myweather {
  width: 200px;
  height: 100px;
}
.user_name {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}
.welcome {
  color: #fff;
  font-size: 16px;
}
.cityposition {
  color: #fff;
  float: right;
}
.cityposition i {
  font-size: 20px;
  vertical-align: middle;
}

.curtime {
  color: #fff;
  float: right;
  line-height: 2;
  text-align: right;
}
.weathercard {
  position: relative;
}
.bgimg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 160px;
}
.conrow1 {
  position: absolute;
  left: 0;
  top: 0;
  height: 40px;
  width: 100%;
  line-height: 60px;
  padding: 0 20px;
}
.lasttime {
  position: absolute;
  left: 0;
  top: 40px;
  padding: 0 20px;
  color: #bfdbff;
  font-size: 12px;
  line-height: 30px;
}
.weathertime {
  position: absolute;
  left: 0;
  top: 70px;
  padding: 0 20px;
  height: 60px;
}
.weatherinfo{
  width:180px;
  height:60px;
  display:inline-block;
}
.calendarbox {
  position: absolute;
  left: 0;
  top: 140px;
}
</style>
<style>
.classified .card .el-card__header {
  padding: 10px 20px;
}
.dialog1 .el-dialog__body {
  background: rgba(0, 0, 0, 0.15);
  padding: 0;
}
.el-picker-panel-calendar[data-v-0a254c59] {
  color: #606266;
  border: none;
  box-shadow: none;
  background: transparent;
  border-radius: initial;
  line-height: initial;
}
.unitdata {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  margin: 5px auto;
  border-radius: 50%;
}
.available.today .unitdata {
  background: #0067ff;
  color: #fff;
}
.topheader .el-card__header {
  position: absolute;
  width: 100%;
}
.weathercard .el-card__body {
  padding: 0;
}
</style>